/**
 * 主应用入口
 * 负责初始化和页面导航
 */

class App {
    constructor() {
        this.currentPage = 'home';
        this.init();
    }

    init() {
        console.log('🚀 EnglishReadCard 初始化中...');
        
        // 初始化导航
        this.initNavigation();
        
        // 初始化存储
        if (typeof Storage !== 'undefined') {
            console.log('✅ LocalStorage 可用');
        } else {
            console.error('❌ LocalStorage 不可用');
            alert('您的浏览器不支持 LocalStorage，部分功能可能无法使用');
        }
        
        // 初始化各个模块
        this.initModules();
        
        // 等待单词本管理器加载完成后更新界面
        this.waitForWordbookManager();
        
        console.log('✅ 初始化完成');
    }

    /**
     * 等待单词本管理器加载完成
     */
    waitForWordbookManager() {
        const checkInterval = setInterval(() => {
            if (window.wordbookManager && window.wordbookManager.isReady) {
                clearInterval(checkInterval);
                this.updateUI();
                this.updateHomePage();
                console.log('✅ 单词本管理器就绪，界面已更新');
            }
        }, 100);

        // 超时保护（10秒后停止检查）
        setTimeout(() => {
            clearInterval(checkInterval);
            if (!window.wordbookManager || !window.wordbookManager.isReady) {
                console.warn('⚠️ 单词本加载超时');
                console.log('请检查控制台错误信息');
            }
        }, 10000);
    }

    /**
     * 初始化导航
     */
    initNavigation() {
        const navItems = document.querySelectorAll('.nav-item');
        
        navItems.forEach(item => {
            item.addEventListener('click', () => {
                const page = item.dataset.page;
                this.navigateTo(page);
            });
        });

        // 返回按钮
        const backButtons = document.querySelectorAll('.btn-back');
        backButtons.forEach(btn => {
            btn.addEventListener('click', () => {
                this.goBack();
            });
        });

        // 首页快速操作按钮
        const smartRecommendBtn = document.getElementById('btn-smart-recommend');
        if (smartRecommendBtn) {
            smartRecommendBtn.addEventListener('click', () => {
                // TODO: 实现智能推荐
                alert('智能推荐功能开发中...');
            });
        }

        const reviewWrongBtn = document.getElementById('btn-review-wrong');
        if (reviewWrongBtn) {
            reviewWrongBtn.addEventListener('click', () => {
                // TODO: 复习错词
                alert('错词复习功能开发中...');
            });
        }
    }

    /**
     * 导航到指定页面
     */
    navigateTo(pageName) {
        // 隐藏所有页面
        document.querySelectorAll('.page').forEach(page => {
            page.classList.remove('active');
        });

        // 显示目标页面
        const targetPage = document.getElementById(`page-${pageName}`);
        if (targetPage) {
            targetPage.classList.add('active');
        }

        // 更新导航状态
        document.querySelectorAll('.nav-item').forEach(item => {
            item.classList.remove('active');
            if (item.dataset.page === pageName) {
                item.classList.add('active');
            }
        });

        this.currentPage = pageName;

        // 触发页面进入事件
        this.onPageEnter(pageName);
    }

    /**
     * 返回
     */
    goBack() {
        this.navigateTo('home');
    }

    /**
     * 页面进入事件
     */
    onPageEnter(pageName) {
        console.log(`📄 进入页面: ${pageName}`);
        
        // 根据页面触发相应的更新
        switch (pageName) {
            case 'home':
                this.updateHomePage();
                break;
            case 'wordbooks':
                if (window.wordbookManager) {
                    wordbookManager.initWordbookManagePage();
                }
                break;
            case 'history':
                if (window.historyManager) {
                    historyManager.render();
                    historyManager.updateStats();
                }
                break;
            case 'select-wordbooks':
                if (window.wordbookManager) {
                    wordbookManager.initWordbookSelection();
                    // 绑定开始学习按钮
                    const startBtn = document.getElementById('btn-start-study');
                    if (startBtn) {
                        startBtn.onclick = () => this.startStudySession();
                    }
                    // 绑定模式选择
                    const modeCards = document.querySelectorAll('.mode-card');
                    modeCards.forEach(card => {
                        card.addEventListener('click', () => {
                            modeCards.forEach(c => c.classList.remove('active'));
                            card.classList.add('active');
                        });
                    });
                }
                break;
            case 'wrongbook':
                if (window.wrongbookManager) {
                    window.wrongbookManager.render();
                }
                break;
            case 'statistics':
                if (window.statisticsManager) {
                    window.statisticsManager.render();
                }
                break;
        }
    }

    /**
     * 初始化各个模块
     */
    initModules() {
        // 注意：各个模块将在其对应的 js 文件加载后自动初始化
        console.log('📦 等待模块加载...');
        
        // 绑定历史页面按钮
        this.initHistoryPageEvents();
    }

    /**
     * 初始化历史页面事件
     */
    initHistoryPageEvents() {
        // 筛选器事件
        const timeFilter = document.getElementById('history-filter-time');
        const modeFilter = document.getElementById('history-filter-mode');
        
        if (timeFilter) {
            timeFilter.addEventListener('change', () => {
                if (window.historyManager) {
                    historyManager.applyFilter(timeFilter.value, modeFilter.value);
                    historyManager.updateStats();
                }
            });
        }
        
        if (modeFilter) {
            modeFilter.addEventListener('change', () => {
                if (window.historyManager) {
                    historyManager.applyFilter(timeFilter.value, modeFilter.value);
                    historyManager.updateStats();
                }
            });
        }

        // 导出历史按钮
        const exportBtn = document.getElementById('btn-export-history');
        if (exportBtn) {
            exportBtn.addEventListener('click', () => {
                if (window.historyManager) {
                    historyManager.exportHistory();
                }
            });
        }

        // 清空历史按钮
        const clearBtn = document.getElementById('btn-clear-history');
        if (clearBtn) {
            clearBtn.addEventListener('click', () => {
                if (window.historyManager) {
                    historyManager.clearHistory();
                }
            });
        }
    }

    /**
     * 更新首页
     */
    updateHomePage() {
        console.log('🔄 更新首页...');
        
        // 更新单词本网格
        if (window.wordbookManager) {
            if (!window.wordbookManager.isReady) {
                console.warn('⚠️ 单词本管理器还未就绪');
                return;
            }
            
            const wordbooks = window.wordbookManager.getAllWordbooks();
            console.log(`📚 获取到 ${wordbooks.length} 个单词本`);
            this.renderWordbookGrid(wordbooks);
        } else {
            console.warn('⚠️ wordbookManager 不存在');
        }

        // 更新错词本数量
        if (window.wrongbookManager) {
            const wrongCount = window.wrongbookManager.getWrongWordsCount();
            const countElem = document.getElementById('wrongbook-count-home');
            if (countElem) {
                countElem.textContent = wrongCount;
            }
            
            // 如果没有错词，禁用复习按钮
            const reviewBtn = document.getElementById('btn-review-wrong');
            if (reviewBtn) {
                if (wrongCount === 0) {
                    reviewBtn.disabled = true;
                    reviewBtn.textContent = '暂无错词';
                } else {
                    reviewBtn.disabled = false;
                    reviewBtn.textContent = '立即复习 →';
                }
            }
        }
    }

    /**
     * 渲染单词本网格
     */
    renderWordbookGrid(wordbooks) {
        const grid = document.getElementById('wordbook-grid');
        if (!grid) return;

        if (wordbooks.length === 0) {
            grid.innerHTML = `
                <div class="empty-state">
                    <div class="empty-state-icon">📚</div>
                    <h3>还没有单词本</h3>
                    <p>上传 CSV 文件创建你的第一个单词本</p>
                </div>
            `;
            return;
        }

        grid.innerHTML = wordbooks.map(wb => {
            const progress = this.calculateWordbookProgress(wb);
            return `
                <div class="wordbook-card animate-fadeIn">
                    <h3>${wb.name}</h3>
                    <p class="wordbook-meta">${wb.wordCount} 个单词 · ${wb.category || '通用'}</p>
                    <div class="progress-bar">
                        <div class="progress-fill" style="width: ${progress}%"></div>
                    </div>
                    <p class="wordbook-meta">${progress}% 已掌握</p>
                    <div class="wordbook-actions">
                        <button class="btn btn-primary btn-sm" onclick="app.startStudy('${wb.id}')">开始学习</button>
                        <button class="btn btn-secondary btn-sm" onclick="wordbookDetailManager.showDetail('${wb.id}')">详情</button>
                    </div>
                </div>
            `;
        }).join('');
    }

    /**
     * 计算单词本进度
     */
    calculateWordbookProgress(wordbook) {
        if (window.wordbookManager) {
            return wordbookManager.calculateProgress(wordbook);
        }
        return 0;
    }

    /**
     * 开始学习（单个单词本）
     */
    startStudy(wordbookId) {
        console.log('开始学习单词本:', wordbookId);
        
        // 跳转到单词本选择页面
        this.navigateTo('select-wordbooks');
        
        // 初始化单词本选择
        if (window.wordbookManager) {
            wordbookManager.initWordbookSelection();
            
            // 预选该单词本
            if (wordbookId) {
                wordbookManager.selectedWordbooks.add(wordbookId);
                wordbookManager.renderWordbookSelection();
                wordbookManager.updateSelectionSummary();
            }
        }
    }


    /**
     * 开始学习（从选择页面）
     */
    startStudySession() {
        if (!window.wordbookManager) {
            alert('单词本管理器未初始化');
            return;
        }

        const selectedIds = Array.from(wordbookManager.selectedWordbooks);
        if (selectedIds.length === 0) {
            alert('请先选择至少一个单词本');
            return;
        }

        // 获取抽取数量
        const countInput = document.getElementById('select-count');
        const count = parseInt(countInput?.value || 20);

        // 获取抽取策略
        const strategy = document.querySelector('input[name="strategy"]:checked')?.value || 'random';

        // 获取学习模式
        const mode = document.querySelector('.mode-card.active')?.dataset.mode;
        if (!mode) {
            alert('请选择学习模式');
            return;
        }

        // 随机抽取单词
        const words = wordbookManager.randomSelect(selectedIds, count, strategy);
        
        if (words.length === 0) {
            alert('没有可用的单词');
            return;
        }

        console.log(`抽取了 ${words.length} 个单词，模式: ${mode}`);

        // 启动相应的学习模式
        if (mode === 'recitation') {
            this.navigateTo('recitation');
            if (window.recitationManager) {
                recitationManager.start(words);
            }
        } else if (mode === 'dictation') {
            this.navigateTo('dictation');
            if (window.dictationManager) {
                dictationManager.start(words);
            }
        }
    }

    /**
     * 更新全局 UI
     */
    updateUI() {
        this.updateSidebarStats();
        this.updateWrongbookBadge();
    }

    /**
     * 更新侧边栏统计
     */
    updateSidebarStats() {
        // 今日学习单词数
        const todayWords = this.getTodayStudiedWords();
        document.getElementById('today-words').textContent = todayWords;

        // 总词汇量
        if (window.wordbookManager) {
            const totalWords = window.wordbookManager.getTotalWordsCount();
            document.getElementById('total-words').textContent = totalWords;
        }
    }

    /**
     * 更新错词本徽章
     */
    updateWrongbookBadge() {
        if (window.wrongbookManager) {
            const count = window.wrongbookManager.getWrongWordsCount();
            const badges = document.querySelectorAll('#wrongbook-count, .nav-badge');
            badges.forEach(badge => {
                badge.textContent = count;
                badge.style.display = count > 0 ? 'block' : 'none';
            });
        }
    }

    /**
     * 获取今日学习单词数
     */
    getTodayStudiedWords() {
        // TODO: 从学习历史中统计
        return 0;
    }
}

// 全局实例
let app;

// DOM 加载完成后初始化
document.addEventListener('DOMContentLoaded', () => {
    app = new App();
    window.app = app; // 暴露到全局，方便其他模块调用
});

